package com.kaiyidiannao.model.req.model;

import com.kaiyidiannao.data.DataCenter;
import com.kaiyidiannao.https.HttpUtils;
import com.kaiyidiannao.model.Result;
import com.kaiyidiannao.model.req.base.BaseCommand;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

/**
 *   购物车 （post） 异步请求 - 添加商品
 */
public class PostShoppingCarsAdd extends BaseCommand {

    private String TAG = "PostDayDayCouponShoppingCar";
    private String action = "add";//ajax-->add
    private String itemid;
    private String userid;
    private JSONArray data;

    public PostShoppingCarsAdd(String itemid, String userid) {
        this.itemid = itemid;
        this.userid = userid;
    }

    @Override
    public String getRequestUrl() {
        return "http://192.168.29.124:8080/kaiyi/mall/buy.php";
    }

    @Override
    public HashMap<String, String> getRequestParamters() {
        HashMap<String, String> paramters = new HashMap<String, String>();
        paramters.put("action", action);
        paramters.put("userid",userid);

        try {
            data = new JSONArray();
            for (int i = 0 ; i < 4; ++i) {
                JSONObject obj = new JSONObject();
                obj.putOpt("productid", "商品title" + i);
                obj.putOpt("productid", "规格1:" + i);
                obj.putOpt("productid", "商品2" + i);
                data.put(obj);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        paramters.put("post", data.toString());
        return paramters;
    }

    @Override
    public Result go(String url, HashMap<String, String> paramters) { // 联网时后台执行
        // 根据请求参数返回请求数据
        return HttpUtils.postByHttpClient(url, paramters);
    }

    @Override
    public void yes(Result result) { //后台执行完毕后执行
        super.yes(result);
        try {
            JSONObject jsonObject = new JSONObject(result.object.toString());
            DataCenter.code = jsonObject.optString("code");
            DataCenter.msg = jsonObject.optString("msg");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        DataCenter.getInstance().callBacks(DataCenter.flag.SHOPPING_CAR_RESULT_DATA_SUCCESS);
    }

    @Override
    public void no(Result result) {
        super.no(result);
        DataCenter.getInstance().callBacks(DataCenter.flag.SHOPPING_CAR_RESULT_DATA_FAILED);
    }
}
